﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Text;
using System.Data.Linq;

namespace SiteRecord
{
    public partial class RecordsCenter : SecurityBase
    {

        #region 属性

        public DateTime? SelectedDate
        {
            get
            {
                if (Session["SelectedDate"] != null)
                {
                    return (DateTime)Session["SelectedDate"];
                }
                return null;
            }
            set
            {
                Session["SelectedDate"] = value;
            }
        }

        public bool LinqContextChanged = false;
        #endregion

        #region 功能函数

        private void LoadPageStates()
        {
            if (SelectedDate.HasValue)
                val_date.Value = SelectedDate.Value.ToShortDateString();

            tbSearchEngine.Text = Properties.Resources.SearchEngine;
            tbSearchEnginePrefix.Text = Properties.Resources.Prefix;


            rb_SiteList.Text = "";


            if (CurrentUser.UserSites.Count > 0)
            {
                CurrentUser.UserSites.ToList().ForEach(p =>
                {
                    rb_SiteList.Text += String.Format("{0}{1}", p.Url, Environment.NewLine);
                });
            }
        }

        public ArrayList RecordDataSource()
        {
            ArrayList obj = new ArrayList();
            List<Records> source;

            if (SelectedDate.HasValue)
                source = SiteRecordContext.Records.ToList().Where(p => p.ModifyDate.Date >= SelectedDate.Value.Date).ToList();
            else
                source = SiteRecordContext.Records.ToList();

            source.ForEach(p =>
            {
                obj.Add(new
                {
                    站点名 = p.UserSites.SiteName,
                    链接 = p.UserSites.Url,
                    收录数 = p.RecordCount,
                    最后收录时间 = p.RecordDate,
                    抓取时间 = p.ModifyDate,
                    收录链接 = p.SnapshotUrl

                });

            });

            return obj;
        }

        public void RecordsDataBind()
        {
            RecordsView.DataSource = RecordDataSource();
            RecordsView.DataBind();
        }


        private void AppendNewSiteRecord(string url)
        {
            if (!CurrentUser.UserSites.ToList().Exists(p => p.Url == url))
            {
                LinqContextChanged = true;
                UserSites usnew = new UserSites()
                {

                    Userid = CurrentUser.ID,
                    Url = url,
                    Modifydate = DateTime.Now
                };

                SiteRecordContext.UserSites.InsertOnSubmit(usnew);
                SiteRecordContext.SubmitChanges();
            }

        }

        /*
        private void AppendNewRecord(Records record)
        {
            var item = SiteRecordContext.Records.FirstOrDefault(p => p.ModifyDate == record.ModifyDate && p.UserSiteID == record.UserSiteID);

            if (item == null)
            {
                SiteRecordContext.Records.InsertOnSubmit(record);
            }
            else
            {
                item.RecordCount = record.RecordCount;
                item.RecordDate = record.RecordDate;
                item.SnapshotUrl = record.SnapshotUrl;
            }
            SiteRecordContext.SubmitChanges();
        }
        */

        #endregion


        #region 事件

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!TokenIsOk)
            {
                Response.Redirect("index.aspx");
            }
            if (!IsPostBack)
            {
                LoadPageStates();
                RecordsDataBind();
            }
        }

        protected void bt_get_Click(object sender, EventArgs e)
        {
            string inputSiteList = rb_SiteList.Text.RemoveAllEmptyStr();
            List<string> inputList = inputSiteList.Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            CurrentUser.UserSites.ToList().ForEach(p => {
                if (!inputList.Contains(p.Url))
                {
                    LinqContextChanged = true;
                    SiteRecordContext.Records.DeleteAllOnSubmit(SiteRecordContext.Records.Where(q => q.UserSiteID == p.ID));
                    CurrentUser.UserSites.Remove(p);
                }
            });


            inputList.ForEach(p =>
            {
                AppendNewSiteRecord(p);
            });

            if (LinqContextChanged)
                Update();
            CurrentUser.Crawl();

            /*
            RecordEngine newEngine = new RecordEngine();
            CurrentUser.UserSites.ToList().ForEach(siteItem =>
            {
                Records record = newEngine.Load(siteItem.Url);
                record.UserSiteID = siteItem.ID;
                siteItem.SiteName = newEngine.Title;

                AppendNewRecord(record);
            });
            */


            RecordsDataBind();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {

        }

        protected void RecordsView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string ErrorInfo = "<span class=\"m-ico-error\">Error</span>";

            if (e.Row.RowType != DataControlRowType.DataRow) return;

            int recordCount = -1;
            if (e.Row.DataItem == null) return;
            PropertyInfo recordR = e.Row.DataItem.GetType().GetProperty("收录数");
            PropertyInfo SnapUrl = e.Row.DataItem.GetType().GetProperty("收录链接");
            PropertyInfo SiteUrl = e.Row.DataItem.GetType().GetProperty("链接");

            if (recordR == null || SnapUrl == null) return;

            string Url = SnapUrl.GetValue(e.Row.DataItem, null).EToString();
            string siteUrl = SiteUrl.GetValue(e.Row.DataItem, null).EToString();

            if (Url.IsNullOrEmpty())
            {
                e.Row.Cells[0].Text += String.Format("<a href='{0}' target='_blank'>没有收录首页</a>", string.Format(Utility.SearchEngineUrl, Utility.Prefix, siteUrl));
            }



            if (int.TryParse(recordR.GetValue(e.Row.DataItem, null).EToString(), out recordCount))
            {
                if (recordCount == 0)
                    e.Row.Cells[0].Text += ErrorInfo;
            }



            e.Row.Cells[1].Attributes.Add("class", "text");


        }

        protected void RecordsView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView gv = (GridView)sender;
            gv.PageIndex = e.NewPageIndex;

            RecordsDataBind();
        }

        protected void Btn_ExportClick(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = Encoding.Default;
            RecordsView.AllowPaging = false;
            RecordsDataBind();

            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter htw = new HtmlTextWriter(sw);

                RecordsView.RenderControl(htw);
                // Style is added dynamically
                Response.Write(@"<style> .text { mso-number-format:\@; } </script> ");
                Response.Write(sw.ToString());
            }
            Response.End();
        }

        protected void btSearch_Click(object sender, EventArgs e)
        {
            DateTime selectedDate = DateTime.Now;
            if (DateTime.TryParse(val_date.Value, out selectedDate))
            {
                this.SelectedDate = selectedDate;
                RecordsDataBind();
            }

        }
        #endregion




    }
}